<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';
import type { GroupVO } from '#/api/register/group/model';

import { ref } from 'vue';
import { useRouter } from 'vue-router';

import { Page, useVbenDrawer, useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { getVxePopupContainer } from '@vben/utils';

import {
  Dropdown,
  Menu,
  MenuItem,
  message,
  Modal,
  Popconfirm,
  Space,
  Tooltip,
} from 'ant-design-vue';

import {
  useVbenVxeGrid,
  vxeCheckboxChecked,
  vxeCheckboxCheckedCount,
} from '#/adapter/vxe-table';
import {
  groupDownloadEntryCode,
  groupDownloadImportTemplate,
  groupExport,
  groupImport,
  groupInfo,
  groupPage,
  groupRemove,
} from '#/api/register/group';
import addGroupToFavoriteModal from '#/components/favorite/src/add-group-modal.vue';
import importModal from '#/components/import/src/import-modal.vue';
import { DetailsModal } from '#/components/modal';
import { commonDownloadExcel, openWindow } from '#/utils/file/download';
import { downloadGYZMiniProQrcode } from '#/utils/wechat';

import addToBusTaskModal from './components/add-bus-task-modal.vue';
import groupMemberDrawer from './components/group-member-drawer.vue';
import { columns, detailsSchema, querySchema } from './data';
import groupDrawer from './group-drawer.vue';
import mergeModal from './merge-modal.vue';
import transferModal from './transfer-modal.vue';

const searchData = ref<Record<string, any>>();
const total = ref(0);
const router = useRouter();
const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 90,
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
  fieldMappingTime: [
    //   [
    //     'createTime',
    //     ['createTimeStart', 'createTimeEnd'],
    //     ['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59'],
    //   ],
    [
      'registerGroupNum',
      ['registerGroupNumStart', 'registerGroupNumEnd'],
      (value) => value,
    ],
    [
      'addressMap',
      ['countryCode', 'provinceCode', 'cityCode', 'districtCode'],
      null,
    ],
  ],
};

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
    // 点击行选中
    // trigger: 'row',
  },
  columns,
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        const queryData = {
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        };
        searchData.value = queryData;

        const resp = await groupPage(queryData);

        total.value = resp.total;

        return resp;
      },
    },
  },
  rowConfig: {
    keyField: 'id',
    isCurrent: true,
  },
  // 表格全局唯一表示 保存列配置需要用到
  id: 'register-group-index',
};

const [BasicTable, tableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

const [GroupDrawer, drawerApi] = useVbenDrawer({
  connectedComponent: groupDrawer,
});

function handleAdd() {
  drawerApi.setData({});
  drawerApi.open();
}

async function handleEdit(row: GroupVO) {
  drawerApi.setData({ id: row.id });
  drawerApi.open();
}

const [GroupDetailsModal, detailsModalApi] = useVbenModal({
  connectedComponent: DetailsModal,
});

function handlePreview(record: GroupVO) {
  detailsModalApi.setData(record);
  detailsModalApi.open();
}

async function handleDelete(row: GroupVO) {
  await groupRemove(row.id);
  await tableApi.query();
}

// 导入
const [ImportModal, importModalApi] = useVbenModal({
  connectedComponent: importModal,
  destroyOnClose: true,
});

function handleImport() {
  importModalApi.setData({});
  importModalApi.open();
}

async function handleImportSuccess() {
  await tableApi.reload();
}

// 导出
function handleExportMenuClick(e: any) {
  const type = e.key;
  if (type === 'data') {
    // 列表数据
    commonDownloadExcel(
      groupExport,
      '参观团数据',
      tableApi.formApi.form.values,
      {
        fieldMappingTime: formOptions.fieldMappingTime,
      },
    );
  }
  if (type === 'certificate') {
    // 证件
    message.warning('待开发');
  }
}

// 合并
const [MergeModal, mergeModalApi] = useVbenModal({
  connectedComponent: mergeModal,
  destroyOnClose: true,
});

function handleMerge() {
  const records = tableApi.grid.getCheckboxRecords();
  mergeModalApi.setData({ records });
  mergeModalApi.open();
}

// 转移跟进人
const [TransferModal, transferModalApi] = useVbenModal({
  connectedComponent: transferModal,
  destroyOnClose: true,
});

function handleTransfer() {
  const records = tableApi.grid.getCheckboxRecords();
  const ids = records.map((v) => v.id);
  transferModalApi.setData({ ids });
  transferModalApi.open();
}

// 批量加入收藏夹
const [AddGroupToFavoriteModal, addGroupToFavoriteModalApi] = useVbenModal({
  connectedComponent: addGroupToFavoriteModal,
  destroyOnClose: true,
});

function handleFavorite() {
  // 勾选加入
  const records = tableApi.grid.getCheckboxRecords();
  addGroupToFavoriteModalApi.setData({
    type: 'check',
    records,
    total: records.length,
  });
  addGroupToFavoriteModalApi.open();
}

function handleMultiDelete() {
  const rows = tableApi.grid.getCheckboxRecords();
  const ids = rows.map((row: GroupVO) => row.id);
  Modal.confirm({
    title: '提示',
    okType: 'danger',
    content: `确认删除选中的${ids.length}条记录吗？`,
    onOk: async () => {
      await groupRemove(ids);
      await tableApi.query();
    },
  });
}

// 查看巴士
const [AddToBusTaskModal, addToBusTaskModalApi] = useVbenModal({
  connectedComponent: addToBusTaskModal,
  destroyOnClose: true,
});

function handleAddToBusTask(row: GroupVO) {
  addToBusTaskModalApi.setData({ groupId: row.id });
  addToBusTaskModalApi.open();
}

function handleEditBusTask(row: GroupVO) {
  addToBusTaskModalApi.setData({ groupId: row.id, update: true });
  addToBusTaskModalApi.open();
}

// 下载入场码
async function downloadEntryCode(row: GroupVO) {
  const zipUrl = await groupDownloadEntryCode(row.id);
  if (zipUrl) {
    openWindow(zipUrl);
  }
}

// 分享小程序码
async function downloadMiniProCode(row: GroupVO) {
  await downloadGYZMiniProQrcode(
    `pages/visitor/register/group/form?mobile=${row.masterMobile}&groupId=${row.id}`,
    `${row.name}_分享码`,
  );
}

// 去呼叫
function handleCall(row: GroupVO) {
  router.push({
    path: `/contact/task/listWorkbench`,
    query: { type: 'group', groupId: row.id },
  });
}

// 查看参观团成员
const [GroupMemberDrawer, groupMemberDrawerApi] = useVbenDrawer({
  connectedComponent: groupMemberDrawer,
  destroyOnClose: true,
});

function handleViewMember(row: GroupVO) {
  groupMemberDrawerApi.setData({ groupId: row.id, name: row.name });
  groupMemberDrawerApi.open();
}
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable>
      <template #table-title>
        <main-title text="参观团列表" />
      </template>
      <template #toolbar-tools>
        <Space>
          <a-button
            v-access:code="['register:group:import']"
            @click="handleImport"
          >
            导入
          </a-button>
          <Dropdown>
            <template #overlay>
              <Menu @click="handleExportMenuClick">
                <span v-access:code="['register:group:export']">
                  <MenuItem key="data" :disabled="total === 0">
                    列表数据
                  </MenuItem>
                </span>
                <span v-access:code="['register:group:exportCertificate']">
                  <MenuItem key="certificate" :disabled="total === 0">
                    证件
                  </MenuItem>
                </span>
              </Menu>
            </template>
            <a-button
              v-access:code="[
                'register:group:export',
                'register:group:exportCertificate',
              ]"
              :disabled="total === 0"
            >
              导出
            </a-button>
          </Dropdown>
          <Tooltip
            title="合并多个勾选的参观团，仅合并人员与标签，数据将保留在目标参观团中"
          >
            <a-button
              v-access:code="['register:group:merge']"
              :disabled="vxeCheckboxCheckedCount(tableApi) < 2"
              @click="handleMerge"
            >
              合并({{ vxeCheckboxCheckedCount(tableApi) }})
            </a-button>
          </Tooltip>
          <Tooltip title="将勾选的参观团转移给其他跟进人，仅变更跟进人归属">
            <a-button
              v-access:code="['register:group:transferFollowUp']"
              :disabled="!vxeCheckboxChecked(tableApi)"
              @click="handleTransfer"
            >
              转移跟进人({{ vxeCheckboxCheckedCount(tableApi) }})
            </a-button>
          </Tooltip>
          <a-button
            v-access:code="['register:group:addFavorite']"
            :disabled="!vxeCheckboxChecked(tableApi)"
            @click="handleFavorite"
          >
            加入收藏夹({{ vxeCheckboxCheckedCount(tableApi) }})
          </a-button>
          <a-button
            :disabled="!vxeCheckboxChecked(tableApi)"
            danger
            type="primary"
            v-access:code="['register:group:remove']"
            @click="handleMultiDelete"
          >
            {{ $t('pages.common.delete') }}
          </a-button>
          <a-button
            type="primary"
            v-access:code="['register:group:add']"
            @click="handleAdd"
          >
            {{ $t('pages.common.add') }}
          </a-button>
        </Space>
      </template>
      <template #total="{ row }">
        <a-button type="link" @click="handleViewMember(row)">
          {{ row.sitNum }} / {{ row.total }}
        </a-button>
      </template>
      <template #action="{ row }">
        <Space>
          <ghost-button
            v-access:code="['register:group:query']"
            @click.stop="handlePreview(row)"
          >
            {{ $t('pages.common.info') }}
          </ghost-button>
          <ghost-button
            v-access:code="['register:group:edit']"
            @click.stop="handleEdit(row)"
          >
            {{ $t('pages.common.edit') }}
          </ghost-button>
          <Popconfirm
            :get-popup-container="getVxePopupContainer"
            placement="left"
            title="确认删除？"
            @confirm="handleDelete(row)"
          >
            <ghost-button
              danger
              v-access:code="['register:group:remove']"
              @click.stop=""
            >
              {{ $t('pages.common.delete') }}
            </ghost-button>
          </Popconfirm>
        </Space>
        <Dropdown placement="bottomRight">
          <template #overlay>
            <Menu>
              <span v-access:code="['bus:manager:add']">
                <MenuItem
                  v-if="!row.busId"
                  key="addBus"
                  @click="handleAddToBusTask(row)"
                >
                  加入巴士任务
                </MenuItem>
              </span>
              <span v-access:code="['bus:manager:update']">
                <MenuItem
                  v-if="row.busId"
                  key="editBus"
                  @click="handleEditBusTask(row)"
                >
                  修改巴士任务
                </MenuItem>
              </span>
              <span v-access:code="['register:group:downloadCode']">
                <MenuItem key="entryCode" @click="downloadEntryCode(row)">
                  下载入场码
                </MenuItem>
              </span>
              <span>
                <MenuItem key="shareCode" @click="downloadMiniProCode(row)">
                  分享码
                </MenuItem>
              </span>
              <span v-access:code="['register:group:trrtCall']">
                <MenuItem key="call" @click="handleCall(row)"> 呼叫 </MenuItem>
              </span>
            </Menu>
          </template>
          <a-button
            v-access:code="['bus:manager:add', 'register:group:downloadCode']"
            size="small"
            type="link"
            @click.prevent
          >
            {{ $t('pages.common.more') }}
          </a-button>
        </Dropdown>
      </template>
    </BasicTable>
    <GroupDetailsModal :columns="detailsSchema()" :api="groupInfo" />
    <ImportModal
      :import-api="groupImport"
      :download-api="groupDownloadImportTemplate"
      @reload="handleImportSuccess"
    />
    <TransferModal @reload="tableApi.reload()" />
    <MergeModal @reload="tableApi.reload()" />
    <AddGroupToFavoriteModal @reload="tableApi.reload()" />
    <GroupDrawer @reload="tableApi.reload()" />
    <GroupMemberDrawer @reload="tableApi.reload()" />
    <AddToBusTaskModal @reload="tableApi.reload()" />
  </Page>
</template>
